require 'digest/sha1'
class Employee < ActiveRecord::Base
    belongs_to :warehouse
    has_many :documents
    
	validates_presence_of :name, :surname, :address, :login, :password, :warehouse_id
    validates_length_of :name, :minimum => 2
    validates_length_of :surname, :minimum => 2
    validates_length_of :login, :minimum => 2
    validates_length_of :password, :minimum => 6
    validates_confirmation_of :password
    validates_presence_of :password_confirmation
    validates_uniqueness_of :login
    
    def self.authenticate(login, pass)
        @employee = find(:first, :conditions => ["login = ? AND password = ?", login, sha1(pass)])
        if @employee != nil
            return @employee.login
        else
            return nil
        end
    end
   
    protected

    def self.sha1(pass)
        Digest::SHA1.hexdigest("SAS--#{pass}--")
    end
    
    after_validation_on_create :encrypt_password
    after_validation_on_update :encrypt_password
    
    def encrypt_password
        write_attribute("password", self.class.sha1(password))
    end
end
